package KiemTra;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.print.attribute.SupportedValuesAttribute;
import javax.swing.*;

public class BaiTap01 extends JFrame{

	public BaiTap01(){
		super("Giải phuong trình bậc 2");
		setSize(380, 160);
		setVisible(true);
		
		final JTextField hsA = new JTextField(5);
		final JTextField hsB = new JTextField(5);
		final JTextField hsC = new JTextField(5);
		final JTextField kq = new JTextField(25);
		JButton bGiai = new JButton("Giải");
		JButton bXoa = new JButton("Xóa");
		JButton bThoat = new JButton("Thoát");
	
		
		JPanel p = new JPanel();
		p.setLayout(new GridLayout(4,1));
		
		JPanel p1 = new JPanel();
		JLabel tieude = new JLabel("Giải PT bậc 2: ax^2 + bx + c = 0");
		tieude.setFont(new Font(getName(), Font.BOLD, 15));
		tieude.setForeground(Color.BLUE);
		p1.add(tieude);
		p.add(p1);
		
		JPanel p2 = new JPanel();
		//p2.setLayout(new GridLayout(1,6));
		p2.add(new JLabel("Hệ số a:")); p2.add(hsA);
		p2.add(new JLabel("Hệ số b:")); p2.add(hsB);
		p2.add(new JLabel("Hệ số c:")); p2.add(hsC);
		p.add(p2);
		
		JPanel p3 = new JPanel();
		p3.add(new JLabel("Kết quả:"));
		p3.add(kq);
		p.add(p3);
		
		JPanel p4 = new JPanel();
		p4.add(bGiai);
		p4.add(bXoa);
		p4.add(bThoat);
		p.add(p4);
		
		this.add(p);
		
		
		bThoat.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
				
			}
		});
		
		bXoa.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				hsA.setText(null);
				hsB.setText(null);
				hsC.setText(null);
				kq.setText(null);
			}
		});
		
		bGiai.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {				
				try{				
					float a,b,c;					
					a = Float.parseFloat(hsA.getText());
					b = Float.parseFloat(hsB.getText());
					c = Float.parseFloat(hsC.getText());
					if(a == 0){
						kq.setText("Không phải phương trình bậc 2!");
					}
					else {
						float delta = b*b - 4*a*c;
						
						if(delta < 0){
							kq.setText("Phương trình vô nghiệm");
						}
						else {
							if(delta == 0){
								float x = -b/(2*a);
								kq.setText("X = " + x);
							}
							else {
								float x1,x2;								
								x1 = (float) (-b + Math.sqrt(delta))/(2*a);
								x2 = (float) (-b - Math.sqrt(delta))/(2*a);
								kq.setText("X1 = " + x1 + ", X2 = " + x2);
							}
						}
					}
				}
				catch (Exception ex) {
					kq.setText("Nhập liệu không đúng!");
				}
								
			}
		});
	}
	
	public static void main(String[] args) {
		new BaiTap01();

	}

}
